import React, { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import {
  X,
  Save,
  FileText,
  HelpCircle,
} from "lucide-react";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";

export default function SchemeForm({
  scheme,
  onSubmit,
  onCancel,
  methodTemplates = [],
  tensionSections = [], // 勘查单列表（必传，格式: [{id, name, ...}, ...]）
  selectedTensionSection = null, // 预选中的勘查单
  disabled = false, // 表单禁用状态（如离线时）
}) {
  // 表单数据状态
  const [formData, setFormData] = useState({
    name: "",
    tensionSectionId: "",
    approvalStatus: "notStarted",
    version: "1.0",
    constructionMethod: ""
  });
  // 表单验证错误
  const [errors, setErrors] = useState({});

  // 初始化表单数据（编辑/新建场景）
  useEffect(() => {
    if (scheme) {
      // 编辑模式：从已有方案加载数据
      setFormData({
        name: scheme.name || "",
        tensionSectionId: scheme.tensionSectionId || "",
        approvalStatus: scheme.approvalStatus || "notStarted",
        version: scheme.version || "1.0",
        constructionMethod: scheme.constructionMethod || ""
      });
    } else {
      // 新建模式：自动生成初始数据
      // 优先使用预选中的勘查单，无则默认选第一个有效勘查单
      const validSections = tensionSections.filter(section => 
        section?.id && section.id.trim() !== "" && section.name
      );
      const initialSectionId = selectedTensionSection?.id || (validSections.length > 0 ? validSections[0].id : "");
      const sectionName = selectedTensionSection?.name || 
        validSections.find(s => s.id === initialSectionId)?.name || "未知勘查单";

      setFormData({
        name: `${sectionName}施工方案`,
        tensionSectionId: initialSectionId,
        approvalStatus: "notStarted",
        version: "1.0",
        constructionMethod: ""
      });
    }
  }, [scheme, selectedTensionSection, tensionSections]);

  // 处理表单字段变更
  const handleFieldChange = (field, value) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    // 清除对应字段的错误提示
    if (errors[field]) {
      setErrors(prev => ({ ...prev, [field]: "" }));
    }
  };

  // 表单验证
  const validate = () => {
    const newErrors = {};
    if (!formData.name?.trim()) {
      newErrors.name = "方案名称不能为空";
    }
    if (!formData.tensionSectionId?.trim()) {
      newErrors.tensionSectionId = "必须关联一个勘查单";
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // 提交表单
  const handleSubmit = (e) => {
    e.preventDefault();
    if (validate() && !disabled) {
      onSubmit(formData);
    }
  };

  // 过滤有效勘查单（避免渲染无效数据）
  const validTensionSections = tensionSections.filter(section => 
    section?.id && section.id.trim() !== "" && section.name
  );

  return (
    <div 
      className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4" 
      onClick={onCancel}
    >
      <div 
        className="bg-white rounded-lg shadow-2xl w-full max-w-lg transform transition-all" 
        onClick={e => e.stopPropagation()}
      >
        <CardHeader className="bg-blue-50 border-b">
          <div className="flex justify-between items-center">
            <CardTitle className="flex items-center gap-2 text-xl">
              <FileText className="w-5 h-5 text-blue-600" />
              {scheme?.id ? "编辑施工方案" : "创建施工方案"}
            </CardTitle>
            <Button 
              variant="ghost" 
              size="icon" 
              onClick={onCancel}
              disabled={disabled}
              className="hover:bg-blue-100"
            >
              <X className="w-4 h-4" />
            </Button>
          </div>
          <CardDescription>
            填写核心信息{scheme?.id ? "更新方案" : "创建方案"}，详细内容可在后续补充
          </CardDescription>
        </CardHeader>
        
        <CardContent className="p-6">
          <form onSubmit={handleSubmit} className="space-y-5">
            {/* 方案名称 */}
            <div className="space-y-2">
              <div className="flex items-center gap-1">
                <Label htmlFor="name" className="font-medium">
                  方案名称<span className="text-red-500">*</span>
                </Label>
                <TooltipProvider>
                  <Tooltip>
                    <TooltipTrigger asChild>
                      <HelpCircle className="w-4 h-4 text-gray-400 cursor-help" />
                    </TooltipTrigger>
                    <TooltipContent>
                      <p className="max-w-xs text-sm">建议包含勘查单名称，便于识别</p>
                    </TooltipContent>
                  </Tooltip>
                </TooltipProvider>
              </div>
              <Input
                id="name"
                value={formData.name || ""}
                onChange={(e) => handleFieldChange("name", e.target.value)}
                placeholder="例如：XX线路勘查单施工方案"
                disabled={disabled}
                className={errors.name ? "border-red-300 focus:ring-red-200" : ""}
              />
              {errors.name && (
                <p className="text-sm text-red-500 flex items-center gap-1">
                  <X className="w-3 h-3" /> {errors.name}
                </p>
              )}
            </div>

            {/* 关联勘查单 */}
            <div className="space-y-2">
              <div className="flex items-center gap-1">
                <Label htmlFor="tensionSectionId" className="font-medium">
                  关联勘查单<span className="text-red-500">*</span>
                </Label>
              </div>
              <Select
                value={formData.tensionSectionId || ""}
                onValueChange={(value) => handleFieldChange("tensionSectionId", value)}
                disabled={disabled || validTensionSections.length === 0}
              >
                <SelectTrigger className={errors.tensionSectionId ? "border-red-300 focus:ring-red-200" : ""}>
                  <SelectValue placeholder={validTensionSections.length === 0 ? "暂无勘查单数据" : "选择关联的勘查单"} />
                </SelectTrigger>
                <SelectContent>
                  {validTensionSections.length > 0 ? (
                    validTensionSections.map((section) => (
                      <SelectItem key={section.id} value={section.id}>
                        {section.name}
                        {section.code && <span className="text-xs text-gray-500 ml-2">({section.code})</span>}
                      </SelectItem>
                    ))
                  ) : (
                    <SelectItem value="" disabled>
                      请先创建勘查单
                    </SelectItem>
                  )}
                </SelectContent>
              </Select>
              {errors.tensionSectionId && (
                <p className="text-sm text-red-500 flex items-center gap-1">
                  <X className="w-3 h-3" /> {errors.tensionSectionId}
                </p>
              )}
              {validTensionSections.length === 0 && (
                <p className="text-xs text-amber-500 flex items-center gap-1">
                  <HelpCircle className="w-3 h-3" /> 请先在勘察单管理中创建勘查单
                </p>
              )}
            </div>

            {/* 施工方法 */}
            <div className="space-y-2">
              <Label htmlFor="constructionMethod" className="font-medium">
                施工方法模板
              </Label>
              <Select
                value={formData.constructionMethod || ""}
                onValueChange={(value) => handleFieldChange("constructionMethod", value)}
                disabled={disabled || methodTemplates.length === 0}
              >
                <SelectTrigger>
                  <SelectValue placeholder={methodTemplates.length === 0 ? "暂无模板数据" : "选择施工方法模板"} />
                </SelectTrigger>
                <SelectContent>
                  {methodTemplates.length > 0 ? (
                    methodTemplates.map((template) => (
                      <SelectItem key={template.id} value={template.id}>
                        {template.methodName}
                      </SelectItem>
                    ))
                  ) : (
                    <SelectItem value="" disabled>
                      暂无可用模板
                    </SelectItem>
                  )}
                </SelectContent>
              </Select>
              {methodTemplates.length === 0 && (
                <p className="text-xs text-gray-500">
                  未配置施工方法模板，可直接填写自定义方法
                </p>
              )}
            </div>

            {/* 操作按钮 */}
            <div className="flex justify-end gap-3 pt-4 border-t mt-2">
              <Button 
                type="button" 
                variant="outline" 
                onClick={onCancel}
                disabled={disabled}
                className="min-w-[80px]"
              >
                取消
              </Button>
              <Button 
                type="submit"
                disabled={disabled}
                className="min-w-[80px] bg-blue-600 hover:bg-blue-700"
              >
                <Save className="w-4 h-4 mr-2" />
                {scheme?.id ? "保存" : "创建"}
              </Button>
            </div>
          </form>
        </CardContent>
      </div>
    </div>
  );
}